package leetcode.l0530;

import leetcode.l0529.Easy_反转链表_206;

import java.util.concurrent.Executors;

/**
 * @author Retain
 * @date 2021/5/30 15:37
 */
public class Easy_回文链表_234 {
    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        Easy_回文链表_234 p = new Easy_回文链表_234();
        System.out.println(p.isPalindrome(node1));
    }

    /**
     * 快慢指针
     * @param head
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head;
        // 快指针先走到末尾，慢指针正好在中间
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 反转后半部分链表 此时slow为反转后的头指针，head前半部分和后半部分已经分开，依次比较节点的值
        slow = reverse(slow.next);
        //
        while (slow != null) {
            if (head.val != slow.val) {
                return false;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;

    }

    /**
     * 递归反转链表
     * @param node
     * @return
     */
    public ListNode reverse(ListNode node) {
        if (node.next == null) {
            return node;
        }
        // newHead是最后一个节点，也是新的首节点
        ListNode newHead = reverse(node.next);
        //
        node.next.next = node;
        node.next = null;
        return newHead;
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
